package com.timedomain.him.remake.utils;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;

import com.timedomain.him.remake.Program;
import com.timedomain.him.remake.receiver.MorningCallAlarmReceiver;

import java.io.File;
import java.util.List;
import java.util.Set;

public class MorningCallManager {

    public static long getNextTime(){



        if(AppSettings.nightChat && AppSettings.nightChatRequiredMorningCall){
            return AppSettings.manualMorningCallDate;
        }
        else{


            if(!AppSettings.nightChat && !AppSettings.morningCallIsManual){
                long date =
                        TimeUtils.dateStampToTimeStamp(TimeUtils.toDateStamp(TimeUtils.getTimeStampIgnoreTimeZone()));

                if(AppSettings.morningCallDateStamp == 0){
//                    AppSettings.firstRun = false;
                    AppSettings.morningCallDateStamp = TimeUtils.toDateStamp(TimeUtils.getTimeStampIgnoreTimeZone());
//                    DB.MorningCall.Add(new com.timedomain.him.remake.models.MorningCall(
//                            TimeUtils.getByDateTime(2023,3,24,9,0,0),
//                            "初次见面","1分6秒","03月24日 09:00",false,FileUtils.pathCombine("morningcall", "initial/初次见面.ogg")
//                    ));
                }

                if(AppSettings.morningCallDateStamp >= TimeUtils.toDateStamp(TimeUtils.getTimeStampIgnoreTimeZone())){
                    date += 86400000L;
                }

                long hourAndMinute = (AppSettings.morningCallHour - TimeUtils.hoursThatBeginOfDay) * 3600000L +
                        AppSettings.morningCallMinute * 60000L;

                return hourAndMinute + date;
            }



            return -1;
        }
    }

    private static boolean isDayOnStopService(){
        long targetDay = TimeUtils.toDateStamp(TimeUtils.getByDateTime(2023,7,31,6,0,0));
        long today = TimeUtils.toDateStamp(TimeUtils.getTimeStampIgnoreTimeZone());
        return targetDay == today;
    }

    // 逻辑：
    /*
    周六周日：100%周末电话
    工作日：70%非周末电话+30%工作日电话
    */

    public static String pullOneNewMorningCall(Context ctx){
        reloadMorningCallsIfRequired(ctx);

        Set<String> target = null;
        String targetPath = "";


        if(TimeUtils.isWeekend(TimeUtils.getTimeStampIgnoreTimeZone())){
            if(TimeUtils.isSaturnday(TimeUtils.getTimeStampIgnoreTimeZone())){
                target = AppSettings.unreadWeekendMorningCall;
                targetPath = "weekend";
            }
            else{

                    target = AppSettings.unreadWeekendMorningCall;
                    targetPath = "weekend";

            }
        }
        else{
            if (Math.random() < 0.3d) {
                target = AppSettings.unreadWeekDayMorningCall;
                targetPath = "weekday";
            }
            else {
                target = AppSettings.unreadNeuralMorningCall;
                targetPath = "neural";
            }
        }

        String[] arr = new String[0];
        arr = target.toArray(arr);

        int index = (int)(Math.random() * (double)arr.length);
        if(index >= arr.length){index = arr.length -1;}

        String name = targetPath+"/"+arr[index]+".ogg";
        target.remove(arr[index]);
        AppSettings.saveSettings(ctx);
        return name;
    }

    private static void reloadMorningCallsIfRequired(Context ctx){
        boolean modified = false;
        if(AppSettings.unreadNeuralMorningCall.isEmpty()){
            modified = true;
            loadToCollection(FileUtils.pathCombine("morningcall","neural"),AppSettings.unreadNeuralMorningCall);
        }
        if(AppSettings.unreadWeekDayMorningCall.isEmpty()){
            modified = true;
            loadToCollection(FileUtils.pathCombine("morningcall","weekday"),AppSettings.unreadWeekDayMorningCall);
        }
        if(AppSettings.unreadWeekendMorningCall.isEmpty()){
            modified = true;
            loadToCollection(FileUtils.pathCombine("morningcall","weekend"),AppSettings.unreadWeekendMorningCall);
        }
        if(modified){
            AppSettings.saveSettings(ctx);
        }
    }

    private static void loadToCollection(String path, Set<String> target){

        List<String> files = FileUtils.listFiles(path,(dir,f) -> f.toLowerCase().endsWith(".ogg"));
        for (String oneFile : files) {
            String name = FileUtils.getFileNameWithoutExtension(oneFile);
            target.add(name);
        }
    }

    public static void setNextMorningCall(Context ctx){
        long nextTime = getNextTime();
        AppSettings.saveSettings(ctx);

        AlarmManager alarmManager = (AlarmManager)ctx.getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(ctx, MorningCallAlarmReceiver.class);
        if(nextTime != -1 && nextTime < TimeUtils.getTimeStampIgnoreTimeZone()){
            ctx.sendBroadcast(intent);
            return;
        }
        PendingIntent pi = PendingIntent.getBroadcast(ctx,431,intent,PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT);
        if(nextTime == -1){
            alarmManager.cancel(pi);
            return;
        }
        AlarmManager.AlarmClockInfo alarmInfo = new AlarmManager.AlarmClockInfo(
                TimeUtils.toSystemTimeStamp(nextTime),
                pi
        );
        alarmManager.setAlarmClock(alarmInfo,pi);
        HLog.d("MorningCall", "setNextAlarmClock: success");
    }

}
